import React, { useState, useEffect, useRef } from "react";

const Countdown = () => {
  const [seconds, setSeconds] = useState(60);
  const [isFinished, setIsFinished] = useState(false);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // 组件挂载时开始倒计时
  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setSeconds((prevSeconds) => {
        if (prevSeconds <= 1) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
          }
          setIsFinished(true);
          return 0;
        }
        return prevSeconds - 1;
      });
    }, 1000);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  // 重置函数
  const handleReset = () => {
    // 清除现有的定时器
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }

    // 重置状态
    setSeconds(60);
    setIsFinished(false);

    // 重新启动定时器
    intervalRef.current = setInterval(() => {
      setSeconds((prevSeconds) => {
        if (prevSeconds <= 1) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
          }
          setIsFinished(true);
          return 0;
        }
        return prevSeconds - 1;
      });
    }, 1000);
  };

  return (
    <div className="countdown-container">
      <div className="countdown-display">
        <h1>倒计时: {seconds} 秒</h1>
      </div>

      {isFinished && (
        <div className="finished-message">
          <p>时间到了！</p>
        </div>
      )}

      <div className="reset-button-container">
        <button onClick={handleReset} className="reset-button">
          重置
        </button>
      </div>
    </div>
  );
};

export default Countdown;
